/* ===================================================
	1. modal window
		$('#editRecip').on('click', function(event) {
          // event.preventDefault ? event.preventDefault() : event.returnValue = false;
          // var URL = '/action?'+'&amp;param1=xxx &amp;param2=xxx';
          // loadAjaxHTML(URL, 'updateRes', 'true');
        // })  
	2. dropdown list
		<div class="row-fluid form-padded">
		  <div class="span8 offset2">
			<div class="control-group">
			  <label class="control-label" for="ChangeType">What would you like to change?</label>
			  <div class="controls">
				<div class="btn-group">
				  <a class="btn dropdown-toggle visible-desktop" data-name="ChangeWhat" data-toggle="dropdown" href="#" >Select&nbsp;<span class="icon-caret-down"></span></a>
				  <ul class="dropdown-menu">
					<xsl:if test="//ShowChangePaymentAccount = 'true'">
					  <li class=""><a data-target="#payment-account-change" data-value="cpa" href="#">Payment account</a></li>
					</xsl:if>
					<li class=""><a data-target="#payment-frequency" data-value="pf" href="#">Payment frequency or next payment date</a></li>
					<xsl:if test="//RateType != 'V'">
					  <li><a data-target="#payment-amount" data-value="pa" href="#">Payment amount</a></li>
					</xsl:if>
					<li class=""><a data-target="#additional-payment" data-value="ap" href="#">Make an additional payment</a></li>
					<xsl:if test="IsVariable='Y'">
					  <li class=""><a data-target="#convert-fixed-rate" data-value="cfa" href="#">Convert to a fixed-rate mortgage</a></li>
					</xsl:if>
				  </ul>
				<select class="hidden-desktop" name="ChangeWhat" id="ChangeWhat" size="1">
				  <option value="cpa" data-target="#payment-account-change">Payment account</option>
				  <option value="pf" data-target="#payment-frequency">Payment frequency or next payment date</option>
				  <option value="pa" data-target="#payment-amount">Payment amount</option>
				  <option value="ap" data-target="#additional-payment">Make an additional payment</option>
				  <option value="cfa" data-target="#convert-fixed-rate">Convert to a fixed-rate mortgage</option>
				</select></div> <!--/ .btn-group -->
			  </div> <!--/ .controls -->
			</div> <!--/ .control-group -->
		  </div>
		</div>
	
	3.	
 ========================================================== */

	 // Function to process a form submission within a container in order to redirect to the same container   
     var containerAjaxFunc = function (containerId, isModal, doValidation) {      
         // console.log('containerAjaxFunc containerId-' + containerId) //to
			// be removed
         var $container =  $('#' + containerId)        
         , setupSubmit = function () { 
    	   // Make sure any submit buttons has the class modal-btn-submit
           $('.modal-btn-submit').on('click', function (event) {
    	     event.preventDefault ? event.preventDefault() : event.returnValue = false; // Cross-browser
																						// support
    	     // console.log('submit') //to be removed
             var $this = $(this)
             , $thisForm = $this.closest('form')
             , doFormValidation = true
           
             if (typeof doValidation != 'undefined' ) {                
              doFormValidation = doValidation
             }
             $(this).prop('disabled', true);
             // Validate form first
             // console.log('doFormValidation-' + doFormValidation) //To be
				// removed
             if (doFormValidation &amp;&amp; $thisForm.valid &amp;&amp; !$thisForm.valid()) { 
                return false;
             }
                
              // form.serialize() does not add the clicked button to the
				// request
              // We need to attach the clicked button as input type=image as
				// hidden field to form so that it can be inserted into the
				// request through the ajax
              var buttonName = $this.attr("name");
                    
              $thisForm.append(
                 $("&lt;input type='hidden'&gt;").attr( { 
                  name: buttonName, 
                  value: buttonName 
                 })
              ); 
              // AJAX synchronous call using Form action
              $.ajax({
                  type     : "POST",
                  url      : $thisForm.attr('action'),
                  data     : $thisForm.serialize(),
                  async  : false,
                  success  : function(data) {
                    if (isModal) {
                      refreshDatepicker();
                    }

                    var link = retrieveLink(data);
                    if (link) {
                      $.get(link, {async:false}, function(data){    
                        refreshHtml(data, containerId, isModal);
                      })                    
                    }  
                    else {
                      refreshHtml(data, containerId, isModal);
                    }
                  }
              });
               return false;
    	    })            
    	  }
        
          , onSuccess = function (refreshLink) {
              /*
				 * This was added to redirect a page when it has a refresh link.
				 * add a hidden div with the id of 'RefreshLinkSection' and add
				 * your link inside that div as text
				 */
              // console.log('refreshlink-'+refreshLink)
                             
              if (refreshLink &amp;&amp; refreshLink.length &gt; 0)
                window.location.href  = refreshLink;
              else 
                window.location.reload();
          }
        
          , refreshHtml = function(data, containerId, isModal) {                         
            var result = $('&lt;div&gt;').html(data)
            var status = result.find('#modalStatus').text()
            var tabStatus = result.find('#modalTabStatus').text()            
            if ( tabStatus == 'true') {
              $container.modal('hide')
              refreshTab()
            } else {
              if (status === 'true') {
                // Hide Modal and refreshes parent page
                onSuccess(result.find('#RefreshLinkSection').text())
              }         
              else {
                loadContainerData(data, containerId, isModal)
              }  
            }   
    	 } 
        setTimeout(setupSubmit,10);
	 }
    
      // Loads content in a container through an Ajax call
      function loadAjaxHTML(link, containerId, modal) {
        var isModal = modal&amp;&amp;modal==='true'?true:false; 
        if (isModal) {  
          refreshDatepicker();
        }
        
        // Needs to set as Synchronous to allow all content to be fetched before
		// loading the container
        $.support.cors = true; // to allow fetch from different domain (on
								// IE8/9)
        $.get(link, {async:false}, function(data){
          var link = retrieveLink(data);
          if (link) {
            $.get(link, function(data){
              loadContainerData(data, containerId, isModal)
	        })                    
	       }  
           else {             
            loadContainerData(data, containerId, isModal)
	       }
         })                  
      } 

      // Loads data html into a container
      function loadContainerData(data, containerId, isModal) {         
         // Remove all instances of css
         var result = $('&lt;div&gt;').html(data)
         
         // Safe fail in case modal window is loaded with non-modal content
         var status = result.find('#modalStatus').text()
         if (status === 'true') {
           // Hide Modal and refreshes parent page
           var refreshLink = result.find('#RefreshLinkSection').text();
           if (refreshLink &amp;&amp; refreshLink.length &gt; 0) {
                window.location.href  = refreshLink;
           }
           else { 
                window.location.reload()
           }
         }
         else {
	         result.find('link[href$=".css"]').remove()
	         if (isModal) {
	           $('#' + containerId + ' .modal-container').html(result);
                $('#' + containerId).trigger('custom-modal-load-complete')
	         }
	         else {
	           $('#' + containerId).html(result);
	         }      
         }
      }      
           	// If Response is coming from an Action Command, it is in the format
			// 'location.replace(url);'.
           	// We need to strip the url from the response
	function retrieveLink(data) {			
    	var link
    	, indexOf = data.indexOf("location.replace(");
    	if (indexOf &gt; -1) {
        	var arrays = data.split("\"");
    		if (arrays &amp;&amp; arrays.length &gt; 0) {
    			link = arrays[1];
	        }
    	}
    	return link;  
	}
	
	// Append Loader to an element
	function addLoader(elem) {
		elem.html('');
		elem.attr('class', 'loader');			
	}
	
	// Remove any Datepicker div to make sure Datepicker pops up on
	// Modal window
	function refreshDatepicker() {				
		if ($('#ui-datepicker-div').length &gt; 0) {				
			$('#ui-datepicker-div').remove();
		}
	}
